﻿var InvoiceGrid = InvoiceGrid || {};
InvoiceGrid = function () {
    var gridInEditMode = false;
    var scratchDropDownChanged = false;
    var InvoiceGridDatasource = new kendo.data.DataSource({
        transport: {
            read: function(options){
                $.ajax({
                    url: "/Invoice/GetInvoice",
                    type: "get",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    cache: false
                   
                });
            },
            create:function(options)
            {
            alert(1);
                debugger;
                var InvoiceVM = new Object();
                InvoiceVM.id = options.data.id;             
                if (options.data.companyId)
                    InvoiceVM.companyId = options.data.companyId.id;

                if (options.data.productRequestId)
                    InvoiceVM.productRequestId = options.data.productRequestId.id;

                InvoiceVM.period = options.data.period;
                InvoiceVM.term = options.data.term;
                InvoiceVM.description = options.data.description;
                InvoiceVM.notes = options.data.notes;
                

                $.ajax({
                    type: "POST",
                    url: "/Invoice/CreateInvoice",
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: JSON.stringify(InvoiceVM),
                    success: function (data) {
                        if (data.Message) {
                            alert(data.Message);
                        }
                        options.success(data);
                    }
                });
            },
                       
            //update: {
            //    url: "/Invoice/UpdateInvoice",
            //    type: 'POST',
            //    dataType: "json",
            //    contentType: "application/JSON"
            //},
            //destroy: {
            //    url: "/Invoice/DeleteInvoice",
            //    type: "POST",
            //    dataType: "json",
            //    contentType: "application/JSON"
            //},
            parameterMap: function (options) {
                return kendo.stringify(options); // kendo.stringify serializes to JSON string
            }

        },

        pageSize: 5,
        schema: {
            model: {
                id: "id",
                fields: {
                    id: {
                        editable: false, nullable: true,
                        type: "int"
                    },                 
                       invoiceDate: {
                        type: "date"
                    },
                    description: {
                        type: "string"
                    },
                    
                    empName: {
                        type: "string"
                    },
                    
                    productName: {
                        type: "string"
                    },
                    compName: {
                        type: "string"
                    },
                    clientContName: {
                        type: "string"
                    },
                    companyId:{
                        type:"int"
                    },
                    
                    notes:
                        {
                            type:"string"
                        },
                    
                    term:
                        {
                            type:"string"
                        },
                    productRequestId:
                        {
                            type:"int"
                        },
                   
                    error: function (a) {
                        debugger;
                        $('#InvoiceGrid').data("kendoGrid").cancelChanges();
                    },

                }
            }
        }

    });
  
    var companyDatasource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/Invoice/GetAllCompanies/",
                type: "get",
                contentType: "application/json",
                dataType: "json"
            }
        }
    });
    var productDatasource = new kendo.data.DataSource({
       
        transport: {
            read: {
                url: "/Invoice/GetAllProductsRequest/",
                type: "GET",
                contentType: "application/json", 
               // data: { number: productRequestId },
                dataType: "json"
            }
        }
    });

    
    return {
        InvoiceGridDatasource: InvoiceGridDatasource,
        gridInEditMode: gridInEditMode,
        companyDatasource: companyDatasource,
        productDatasource:productDatasource,
        scratchDropDownChanged: scratchDropDownChanged
    }
}();




$(function () {

    $(window).on("beforeunload", function () {

        if (InvoiceGrid.gridInEditMode) {
            return "Are you sure you want to discard all your changes."
        }

    });
  
   
    function dateTimeEditor(container, options) {
        $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDateTimePicker({});
    }
    $("#InvoiceGrid").kendoGrid({
        dataSource: InvoiceGrid.InvoiceGridDatasource,
        scrollable: true,
        height: "250px",
        toolbar: [{ name: "create", text: "Add a Ivoice" }, "excel"], //, "save", "cancel"],
        excel: {
            fileName: "InvoiceExport.xlsx"
        },
        pageable: true,
        height: 300,
      
        columns: [
   
    { title: "items", filterable: false, width: "8em", template: "<a onclick=\"showItems('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
        //{ title: "PDF", filterable: false, width: "6em", template: "<a onclick=\"showProjects('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
        //  { title: "SEND", filterable: false, width: "6em", template: "<a onclick=\"showCompanyMessages('#=id #',this);\"style=\"cursor: pointer;\"> View</a>" },
      { field: "compName", title: "BillTo",editor:companyDropDownEditor, filterable: true, width: "8em" },

       {
           field: "invoiceDate", title: "Date", width: "10em", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
           editor: dateTimeEditor,
           filterable: {
               ui: "datetimepicker"
           }
       },

        { field: "productName", title: "Product Name",editor:productDropDownEditor, filterable: true, width: "8em" },
         { field: "term", title: "Term", filterable: true, width: "8em" },
           { field: "notes", title: "Notes", filterable: true, width: "8em" },
     
      {
          title: "&nbsp;",
          width: "25em",
          //command: ["edit", "destroy"]
          command: [

              "edit",
              {
                  name: "Delete",


                  click: function (e) {
                     
                      var tr = $(e.target).closest("tr"); //get the row for deletion
                      var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                      //see what is coming in dataItem
                      //if (dataItem > 0) {
                      //    $("#delValidation").addClass('in')
                      //}
                      //else {

                          deleteTopicConfirmation(e, this);
                      ////}
                      return false;
                  }
              }
          ]
      }
        ],
        filterable: {
            extra: false,
            operators: {
                string: {
                    eq: "Is equal to",
                    neq: "Is not equal to",
                      contains:"Contains"
                }
            }
        },
      
        editable: "popup",
        sortable: {
            mode: "single",
            allowUnsort: false
        },       
        selectable: true,
          
        cancel: function () {
            InvoiceGrid.gridInEditMode = false;
        },
        excelExport: function (e) {
            for (var i = 0; i < e.workbook.sheets[0].columns.length; i++) {
                e.workbook.sheets[0].columns[i].autoWidth = true;
            }
        }
    });

    InvoiceGrid.InvoiceGridDatasource.bind("requestEnd", showSuccessMessage);


    function showSuccessMessage(e) {
        if (e.type === "update" || e.type === "create") {
            InvoiceGrid.gridInEditMode = false;
            $("#saveConfirm").addClass('in');
            e.sender.read();
        }
    }


    $(".close").click(function () {
        $(this).parent().removeClass('in');
    });
    function deleteTopicConfirmation(e, widget) {
        var grid = $('#InvoiceGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }

    function productDropDownEditor(container, options) {

        $('<input id="ProductValue" data-text-field="name" data-value-field="id"  data-bind="value:productRequestId"/>').appendTo(container).kendoDropDownList({
            autoBind: true,
            dataValueField: "id",
            dataTextField: "name",
            dataSource: InvoiceGrid.productDatasource
        });
    }

    function companyDropDownEditor(container, options) {

        $('<input id="cotValue" data-text-field="compName" data-value-field="id"  data-bind="value:companyId"/>').appendTo(container).kendoDropDownList({
            autoBind: true,
            dataValueField: "id",
            dataTextField: "compName",
            dataSource: InvoiceGrid.companyDatasource
        });
    }

    function deleteTopicConfirmation(e, widget) {
        var grid = $('#InvoiceGrid').data("kendoGrid");
        deleteConfirmation(e, widget, grid);
    }

    function deleteConfirmation(e, widget, grid) {

        var currentRow = $(e.target).closest("tr"); //get the row for deletion

        var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

        var kendoWindow = $("<div />").kendoWindow({

            title: "Confirmation",
            resizable: true,
            modal: true,
            width: "400px"
        });

        kendoWindow.data("kendoWindow")

            .content($("#delete-confirmation").html())

            .center().open();

        kendoWindow

            .find(".delete-confirm,.delete-cancel")
            .click(function () {
                if ($(this).hasClass("delete-confirm")) {

                    grid.dataSource.remove(currentRowData);

                    grid.dataSource.sync();

                }

                $(this).closest("[data-role=window]").kendoWindow("close");

            });

    }

});